using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.CompositeUI.WinForms.UIElements;
using System.Windows.Forms;

namespace SCSFContrib.CompositeUI.WinForms.UIElements
{
    /// <summary>
    /// An adapter that wraps a <see cref="ToolStripDropDownItem"/> for use as an <see cref="IUIElementAdapter"/>.
    /// The class extends the behavior of <see cref="ToolStripItemCollectionUIAdapter"/> with enabling/disabling or
    /// showing/hiding of the <see cref="ToolStripDropDownItem"/> in respect to the drop down items count.
    /// </summary>
    public class ToolStripDropDownItemUIAdapter : ToolStripItemCollectionUIAdapter
    {
        private ToolStripDropDownItem dropDownItem;
        private bool hide;

        /// <summary>
        /// Creates an <see cref="IUIElementAdapter"/> for the <see cref="ToolStripDropDownItem"/>. It disables the
        /// dropDownItem if the DropDown.Items collection is empty.
        /// </summary>
        public ToolStripDropDownItemUIAdapter(ToolStripDropDownItem dropDownItem) : this(dropDownItem, false) { }

        /// <summary>
        /// Creates an <see cref="IUIElementAdapter"/> for the <see cref="ToolStripDropDownItem"/>. It disables the
        /// dropDownItem if the DropDown.Items collection is empty.
        /// </summary>
        /// <param name="hide">Set this parameter to true if the adapter should hide the dropDownItem
        /// instead of diabling.</param>
        public ToolStripDropDownItemUIAdapter(ToolStripDropDownItem dropDownItem, bool hide)
            : base(dropDownItem.DropDown.Items)
        {
            this.dropDownItem = dropDownItem;
            this.hide = hide;
            UpdateUI();
        }

        protected override ToolStripItem Add(ToolStripItem uiElement)
        {
            ToolStripItem item = base.Add(uiElement);
            UpdateUI();
            return item;
        }

        protected override void Remove(ToolStripItem uiElement)
        {
            base.Remove(uiElement);
            UpdateUI();
        }

        private void UpdateUI()
        {
            if (hide) { dropDownItem.Visible = (dropDownItem.DropDown.Items.Count > 0); }
            else { dropDownItem.Enabled = (dropDownItem.DropDown.Items.Count > 0); }
        }
    }
}
